/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.opu.pc.bl;

import java.util.Collection;
import org.opu.pc.domain.domains.Publisher;
import org.opu.pc.domain.domains.Publication;
import org.opu.pc.util.DateUtil;

/**
 *
 * @author Yuriy Dunko
 */
public class BibliographyLinkServiceImpl implements BibliographyLinkService{

    @Override
    public String createBibliographyLink(Publication publication) {
        StringBuilder sb = new StringBuilder()
                .append(getAuthorsPart(publication.getPublishers()))
                .append(' ')
                .append(publication.getName())
                .append(" // ")
                .append(publication.getConferenceVenue())
                .append('.');

        if (publication.getDate() != null){
            sb.append(" — ")
                    .append(DateUtil.getYear(publication.getDate()))
                    .append('.');
        }

        Integer startPage = publication.getPageNumberStart();
        sb.append(" — С. ").append(startPage);
        Integer endPage = publication.getPageNumberEnd();

        if (!startPage.equals(endPage) && endPage != null && endPage > 0){
            sb.append('-').append(endPage);
        }

        sb.append('.');

        return sb.toString();
    }


    private String getAuthorsPart(Collection<Publisher> authors) {
        StringBuilder sb = new StringBuilder();
        boolean notFirst = false;
        for (Publisher author : authors) {
            if (notFirst) {
                sb.append(", ");
            }
            notFirst = true;
            sb.append(author.getSecondName()).append(getInitials(author));
        }
        return sb.toString();
    };

    private String getInitials(Publisher author){
        StringBuilder sb = new StringBuilder();
        if (author.getName() != null && !author.getName().isEmpty()){
            sb.append(' ').append(author.getName().charAt(0)).append('.');
            if (author.getLastName() != null && !author.getLastName().isEmpty()){
                sb.append(' ').append(author.getLastName().charAt(0)).append('.');
            }
        }
        return sb.toString();
    }
}
